<template>
  <div class="user-chat">
    <!-- 导航栏 -->
     <van-nav-bar
       title="小智同学"
       left-arrow
       @click-left="$router.back()"
     />
    <!-- /导航栏 -->

    <!-- 消息列表 -->
    <van-cell-group class="message-list">
      <van-cell
        :title="item.msg"
        v-for="(item,index) in messages"
        :key="index"
      />
    </van-cell-group>
    <!-- /消息列表 -->

    <!-- 发送消息 -->
    <van-cell-group class="send-message-wrap">
      <van-field
         v-model="message"
         placeholder="请输入内容"
         :border="false"
      />
      <van-button
         class="send-btn"
         type="primary"
         size="small"
         @click="onSend"
      >发送</van-button>
    </van-cell-group>
    <!-- /发送消息 -->
  </div>
</template>
<script>
  import io from 'socket.io-client'

  export default {
   name: 'UserChat',
	 components:{},
	 props:{},
   data () {
     return {
       message:'',
       socket:null,
       messages:[] //消息列表
     }
   },
	 computed: {},
	 watch: {},
	 created () {
     //建立连接
     const socket = io('http://ttapi.research.itcast.cn/')
     this.socket = socket

     socket.on('connect', function () {
       console.log('连接建立成功了')
     })

     //断开连接了
     socket.on('disconnect', function () {
       console.log('断开连接了')
     })

     //监听message事件,接收服务器端消息
     socket.on('message', function (data){
       console.log(data)
     })
   },
	 mounted() {},
   methods:{
     onSend () {
       const data = {
         msg:this.message,
         timestamp:Date.now()
       }
       this.socket.emit('message',data)

       //把用户发出去的消息存储到数组中
       this.messages.push(data)
       
       //清空输入框
       this.message = ''
     }
   }
  }
</script>

<style scoped lang="less">
  .message-list {
    position:fixed;
    left:0;
    right:0;
    top:46px;
    bottom:44px;
  }
  .send-message-wrap {
    position:fixed;
    left:0;
    right:0;
    bottom:0;
    display:flex;
    align-items: center;
    padding:0 14px;
    .send-btn {
      width:60px;
    }
  }
</style>
